'use strict';

/**
 * @name 权限相关的模块
 * @author Yud
 */

angular.module('metalabPartnerApp').factory('Passport', ['$uibModal', '$uibModalStack', '$rootScope', '$state', 'MetaResources', 'MetaRemind', '$q', '$http', '$window', '$cookies',
    function ($uibModal, $uibModalStack, $rootScope, $state, MetaResources, MetaRemind, $q, $http, $window, $cookies) {
        var passport = {};

        passport.registry = function () {
            $rootScope.passport = $q.defer();
            //登录事件
            $rootScope.$on('signIn', function (event, args) {
                $rootScope.USER_TOKEN = args.token;
                $http.defaults.headers.common['X-Token'] = args.token;
                MetaResources.user.get({id: '_self'}, function (data) {
                    $rootScope.USER = data;
                    $rootScope.passport.resolve('yes');
                }, function (error) {
                    MetaRemind.error(error);
                    $rootScope.$broadcast('signOut');
                });
            });

            //退出事件
            $rootScope.$on('signOut', function () {
                var domain = window.location.hostname.split('.');
                if (domain.length > 2) {
                    domain = domain.splice(domain.length - 2, 2).join('.');
                } else {
                    domain = domain.join('.');
                }
                $cookies.remove('USER_TOKEN', {
                    domain: domain
                });
                delete $rootScope.USER_TOKEN;
                /**
                 * 在合伙人系统中退出将进入到游客系统中
                 * 先清除 onbeforeunload 事件
                 * 再跳转至游客系统
                 */
                $window.onbeforeunload = undefined;
                var href = ($window.location.href.split($window.location.origin)[1]);
                $window.open(CONFIG.visitorHost.split('/#')[0] + href, '_self');
            });

        };

        passport.init = function () {

            if ($cookies.get('USER_TOKEN')) {
                //在signIn事件里触发resolve操作
                $rootScope.$broadcast('signIn', {token: $cookies.get('USER_TOKEN')});
            } else {
                $rootScope.passport.reject('no');
                $rootScope.$broadcast('signOut');
            }

            $rootScope.$on('$stateChangeStart', function () {
                if (!$cookies.get('USER_TOKEN')) {
                    $rootScope.$broadcast('signOut');
                }
            });
            /**
             * 使用promise对象，保证只有拿到X-Token后才进入正式的页面
             */
            $rootScope.passport.promise.then(function () {
                //此时注册 stateChangeStart事件
                //在state change start 时触发事件
                $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState) {
                    //如果fromeState页面模式为safe模式,toState页面模式为normal，则需要confirm确认
                    try {
                        if (fromState.data && fromState.data.pageMode && fromState.data.pageMode === 'safe') {
                            if (toState.data.pageMode && toState.data.pageMode === 'normal') {
                                if (!confirm('离开此页，已有信息将不保存，是否确认退出？')) {
                                    event.preventDefault();
                                }
                            } else {
                                console.log('进入兼容页面!');
                            }
                        }
                    } catch (e) {
                        console.error(e);
                    }
                });

                //注册stateChangeSuccess事件
                //在state转变完成后,处理的方法
                $rootScope.$on('$stateChangeSuccess', function (event, toState) {
                    //如果toState中pageMode==='safe',则绑定onbeforeunload事件
                    try {
                        if (toState.data.pageMode && toState.data.pageMode === 'safe') {
                            $window.onbeforeunload = function () {
                                return '离开此页，已有信息将不保存，是否确认退出？';
                            };
                        } else {
                            $window.onbeforeunload = undefined;
                        }
                    } catch (error) {
                        console.error(error);
                        window.onbeforeunload = undefined;
                    }
                });
            });

        };

        passport.isSignIn = function () {
            return $rootScope.USER_TOKEN;
        };

        passport.signOut = function () {
            $rootScope.$broadcast('signOut');
        };

        return passport;
    }]);
